from rest_framework import serializers
from .models import TestSuite, TestCase, TestExecution


class TestSuiteSerializer(serializers.ModelSerializer):
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)
    test_case_count = serializers.SerializerMethodField()

    class Meta:
        model = TestSuite
        fields = [
            'id', 'name', 'description', 'suite_type', 'browser_type',
            'created_by', 'created_by_name', 'created_at', 'updated_at',
            'test_case_count'
        ]
        read_only_fields = ['created_by', 'created_at', 'updated_at']

    def get_test_case_count(self, obj):
        return obj.testcase_set.count()


class TestCaseSerializer(serializers.ModelSerializer):
    suite_name = serializers.CharField(source='suite.name', read_only=True)
    created_by_name = serializers.CharField(source='suite.created_by.username', read_only=True)

    class Meta:
        model = TestCase
        fields = [
            'id', 'suite', 'suite_name', 'name', 'description', 'steps',
            'priority', 'order', 'is_active', 'created_at', 'created_by_name'
        ]
        read_only_fields = ['created_at']


class TestExecutionSerializer(serializers.ModelSerializer):
    suite_name = serializers.CharField(source='suite.name', read_only=True)
    executed_by_name = serializers.CharField(source='executed_by.username', read_only=True)
    duration = serializers.SerializerMethodField()

    class Meta:
        model = TestExecution
        fields = [
            'id', 'suite', 'suite_name', 'status', 'started_at', 'finished_at',
            'total_cases', 'passed_cases', 'failed_cases', 'execution_log',
            'executed_by', 'executed_by_name', 'duration'
        ]
        read_only_fields = ['started_at', 'finished_at', 'executed_by']

    def get_duration(self, obj):
        if obj.finished_at and obj.started_at:
            return (obj.finished_at - obj.started_at).total_seconds()
        return None